package com.speily.zookeeperdemo.lock;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.zookeeper.CreateMode;

/**
 * @Auther: SPL
 * @Date: 2019-08-12 13:26
 * @Description: - 客户端连接状态监听机制,注册监听器，监听节点状态
 */
@Slf4j
public class MyConnectionStateListener implements ConnectionStateListener {

    /*当连接出现异常, 将通过ConnectionStateListener接口进行监听, 并进行相应的处理, 这些状态变化包括:
    暂停(SUSPENDED): 当连接丢失, 将暂停所有操作, 直到连接重新建立, 如果在规定时间内无法建立连接, 将触发LOST通知
    重连(RECONNECTED): 连接丢失, 执行重连时, 将触发该通知
    丢失(LOST): 连接超时时, 将触发该通知*/

    /** 节点路径 */
    private String zkRegPathPrefix;
    /** 节点内容 */
    private String regContent;

    public MyConnectionStateListener(String zkRegPathPrefix, String regContent) {
        this.zkRegPathPrefix = zkRegPathPrefix;
        this.regContent = regContent;
    }

    @Override
    public void stateChanged(CuratorFramework client, ConnectionState newState) {
        if (newState == ConnectionState.LOST) {
            //连接丢失
            log.info("lost session with zookeeper");
            log.info("锁已经释放,不再拥有该锁");
            while(true){
                try {
                    log.info("尝试重新连接......");
                    if(client.getZookeeperClient().blockUntilConnectedOrTimedOut()){
                        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(zkRegPathPrefix, regContent.getBytes("UTF-8"));
                        break;
                    }
                } catch (InterruptedException e) {
                    break;
                } catch (Exception e){
                    //TODO: log something
                }
            }
        } else if (newState == ConnectionState.CONNECTED) {
            //连接新建
            log.info("connected with zookeeper");
        } else if (newState == ConnectionState.RECONNECTED) {
            //重新连接
            log.info("reconnected with zookeeper");
        }
    }
}
